/**
 * 账号管理前端JavaScript
 * 提供用户管理的完整功能实现
 */

class AccountManager {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 10;
        this.searchKeyword = '';
        this.roleFilter = '';
        this.statusFilter = '';
        this.resetUserId = null;
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadUsers();
    }
    
    /**
     * 绑定事件处理
     */
    bindEvents() {
        // 搜索输入框事件
        document.getElementById('searchInput').addEventListener('input', 
            this.debounce(() => {
                this.searchKeyword = document.getElementById('searchInput').value;
                this.currentPage = 1;
                this.loadUsers();
            }, 500)
        );
        
        // 角色过滤事件
        document.getElementById('roleFilter').addEventListener('change', (e) => {
            this.roleFilter = e.target.value;
            this.currentPage = 1;
            this.loadUsers();
        });
        
        // 状态过滤事件
        document.getElementById('statusFilter').addEventListener('change', (e) => {
            this.statusFilter = e.target.value;
            this.currentPage = 1;
            this.loadUsers();
        });
        
        // 添加用户表单提交
        document.getElementById('addUserForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleAddUser();
        });
        
        // 编辑用户表单提交
        document.getElementById('editUserForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleEditUser();
        });
        
        // 修改密码表单提交
        document.getElementById('changePasswordForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleChangePassword();
        });
        
        // 密码强度检查
        document.querySelector('input[name="password"]').addEventListener('input', (e) => {
            this.checkPasswordStrength(e.target.value, 'passwordStrength');
        });
        
        document.querySelector('input[name="new_password"]').addEventListener('input', (e) => {
            this.checkPasswordStrength(e.target.value, 'newPasswordStrength');
        });
        
        // 密码确认检查
        document.querySelector('input[name="confirmPassword"]').addEventListener('input', (e) => {
            this.validatePasswordConfirm('password', 'confirmPassword');
        });
        
        document.querySelector('input[name="confirm_new_password"]').addEventListener('input', (e) => {
            this.validatePasswordConfirm('new_password', 'confirm_new_password');
        });
    }
    
    /**
     * 防抖函数
     */
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
      
    /**
     * 加载用户列表
     */
    async loadUsers() {
        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                size: this.pageSize
            });
            
            if (this.searchKeyword) {
                params.append('search', this.searchKeyword);
            }
            if (this.roleFilter) {
                params.append('role', this.roleFilter);
            }
            if (this.statusFilter !== '') {
                params.append('is_active', this.statusFilter);
            }
            
            const response = await apiRequest(`/api/users/?${params}`);
            
            if (response.code === 200) {
                this.renderUserTable(response.data.users);
                this.renderPagination(response.data.pagination);
            } else {
                this.showNotification(response.message || '加载用户列表失败', 'error');
            }
        } catch (error) {
            console.error('加载用户列表失败:', error);
            this.showNotification('加载用户列表失败', 'error');
        }
    }
    
    /**
     * 渲染用户表格
     */
    renderUserTable(users) {
        const tbody = document.getElementById('userTableBody');
        
        if (users.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="px-6 py-8 text-center text-slate-500">
                        <i class="fas fa-search text-2xl mb-2"></i>
                        <p>没有找到匹配的用户</p>
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = users.map(user => `
            <tr class="hover:bg-slate-50 transition-colors">
                <td class="px-6 py-4 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="w-10 h-10 rounded-full bg-gradient-to-br ${user.role === 'admin' ? 'from-purple-400 to-purple-600' : 'from-blue-400 to-blue-600'} flex items-center justify-center mr-3">
                            <i class="fas fa-user text-white"></i>
                        </div>
                        <div>
                            <div class="text-sm font-medium text-slate-900">${user.username}</div>
                            ${user.full_name ? `<div class="text-xs text-slate-500">${user.full_name}</div>` : ''}
                        </div>
                    </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">${user.email}</td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'
                    }">
                        ${user.role === 'admin' ? '管理员' : '普通用户'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                        user.is_active ? 'bg-green-100 text-green-800' : 'bg-slate-100 text-slate-800'
                    }">
                        <i class="fas fa-circle text-xs mr-1"></i>${user.is_active ? '活跃' : '禁用'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                    ${this.formatDate(user.created_at)}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
                    ${user.last_login ? this.formatDate(user.last_login) : '从未登录'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <div class="flex items-center space-x-2">
                        ${this.getCurrentUser().is_superuser ? `
                            <button onclick="accountManager.showEditUserModal(${user.id})" 
                                    class="text-indigo-600 hover:text-indigo-900 transition-colors" 
                                    title="编辑用户">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="accountManager.showResetPasswordModal(${user.id}, '${user.username}')" 
                                    class="text-orange-600 hover:text-orange-900 transition-colors" 
                                    title="重置密码">
                                <i class="fas fa-key"></i>
                            </button>
                            ${user.role !== 'admin' ? `
                                <button onclick="accountManager.deleteUser(${user.id}, '${user.username}')" 
                                        class="text-red-600 hover:text-red-900 transition-colors" 
                                        title="删除用户">
                                    <i class="fas fa-trash"></i>
                                </button>
                            ` : ''}
                        ` : ''}
                        <button onclick="accountManager.showChangePasswordModal(${user.id})" 
                                class="text-blue-600 hover:text-blue-900 transition-colors" 
                                title="修改密码">
                            <i class="fas fa-lock"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');
    }
    
    /**
     * 渲染分页
     */
    renderPagination(pagination) {
        const paginationDiv = document.getElementById('pagination');
        const { page, size, total, total_pages } = pagination;
        
        let html = `
            <div class="text-sm text-slate-700">
                显示 ${(page - 1) * size + 1}-${Math.min(page * size, total)} 条，共 ${total} 条记录
            </div>
            <div class="flex items-center space-x-2">
        `;
        
        // 上一页按钮
        html += `
            <button onclick="accountManager.goToPage(${page - 1})" 
                    ${page === 1 ? 'disabled' : ''} 
                    class="px-3 py-1 border border-slate-300 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                <i class="fas fa-chevron-left"></i>
            </button>
        `;
        
        // 页码按钮
        for (let i = Math.max(1, page - 2); i <= Math.min(total_pages, page + 2); i++) {
            if (i === 1 && page > 3) {
                html += `<button class="px-3 py-1 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors" onclick="accountManager.goToPage(1)">1</button>`;
                if (i > 2) html += `<span class="px-2">...</span>`;
            }
            
            if (i === page) {
                html += `<button class="px-3 py-1 bg-indigo-600 text-white rounded-lg">${i}</button>`;
            } else {
                html += `<button class="px-3 py-1 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors" onclick="accountManager.goToPage(${i})">${i}</button>`;
            }
            
            if (i === total_pages && page < total_pages - 2) {
                if (i < total_pages - 1) html += `<span class="px-2">...</span>`;
                html += `<button class="px-3 py-1 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors" onclick="accountManager.goToPage(${total_pages})">${total_pages}</button>`;
            }
        }
        
        // 下一页按钮
        html += `
            <button onclick="accountManager.goToPage(${page + 1})" 
                    ${page === total_pages ? 'disabled' : ''} 
                    class="px-3 py-1 border border-slate-300 rounded-lg hover:bg-slate-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                <i class="fas fa-chevron-right"></i>
            </button>
        `;
        
        html += '</div>';
        paginationDiv.innerHTML = html;
    }
    
    /**
     * 跳转到指定页面
     */
    goToPage(page) {
        this.currentPage = page;
        this.loadUsers();
    }
    
    /**
     * 显示添加用户模态框
     */
    showAddUserModal() {
        document.getElementById('addUserModal').classList.remove('hidden');
        document.getElementById('addUserForm').reset();
        document.getElementById('passwordStrength').innerHTML = '';
    }
    
    /**
     * 隐藏添加用户模态框
     */
    hideAddUserModal() {
        document.getElementById('addUserModal').classList.add('hidden');
    }
    
    /**
     * 显示编辑用户模态框
     */
    async showEditUserModal(userId) {
        try {
            const response = await apiRequest(`/api/users/${userId}`);
            if (response.code === 200) {
                const user = response.data;
                const form = document.getElementById('editUserForm');
                
                form.user_id.value = user.id;
                form.username.value = user.username;
                form.email.value = user.email;
                form.full_name.value = user.full_name || '';
                form.phone.value = user.phone || '';
                form.role_ids.value = user.role === 'admin' ? '1' : '2';
                form.is_active.value = user.is_active.toString();
                
                document.getElementById('editUserModal').classList.remove('hidden');
            } else {
                this.showNotification('获取用户信息失败', 'error');
            }
        } catch (error) {
            console.error('获取用户信息失败:', error);
            this.showNotification('获取用户信息失败', 'error');
        }
    }
    
    /**
     * 隐藏编辑用户模态框
     */
    hideEditUserModal() {
        document.getElementById('editUserModal').classList.add('hidden');
    }
    
    /**
     * 显示重置密码模态框
     */
    showResetPasswordModal(userId, username) {
        this.resetUserId = userId;
        document.getElementById('resetUsername').textContent = username;
        document.getElementById('resetPasswordModal').classList.remove('hidden');
    }
    
    /**
     * 隐藏重置密码模态框
     */
    hideResetPasswordModal() {
        document.getElementById('resetPasswordModal').classList.add('hidden');
        this.resetUserId = null;
    }
    
    /**
     * 确认重置密码
     */
    async confirmResetPassword() {
        if (!this.resetUserId) return;
        
        try {
            const response = await apiRequest(`/api/users/${this.resetUserId}/reset-password`, {
                method: 'POST'
            });
            
            if (response.code === 200) {
                this.hideResetPasswordModal();
                this.showNewPassword(response.data.new_password);
                this.showNotification('密码重置成功', 'success');
            } else {
                this.showNotification(response.message || '密码重置失败', 'error');
            }
        } catch (error) {
            console.error('密码重置失败:', error);
            this.showNotification('密码重置失败', 'error');
        }
    }
    
    /**
     * 显示新密码
     */
    showNewPassword(password) {
        document.getElementById('newPasswordValue').textContent = password;
        document.getElementById('newPasswordModal').classList.remove('hidden');
    }
    
    /**
     * 隐藏新密码模态框
     */
    hideNewPasswordModal() {
        document.getElementById('newPasswordModal').classList.add('hidden');
    }
    
    /**
     * 复制密码
     */
    copyPassword() {
        const password = document.getElementById('newPasswordValue').textContent;
        navigator.clipboard.writeText(password).then(() => {
            this.showNotification('密码已复制到剪贴板', 'success');
        }).catch(() => {
            this.showNotification('复制失败，请手动复制', 'error');
        });
    }
    
    /**
     * 显示修改密码模态框
     */
    showChangePasswordModal(userId) {
        const form = document.getElementById('changePasswordForm');
        form.user_id.value = userId;
        form.reset();
        document.getElementById('newPasswordStrength').innerHTML = '';
        document.getElementById('changePasswordModal').classList.remove('hidden');
    }
    
    /**
     * 隐藏修改密码模态框
     */
    hideChangePasswordModal() {
        document.getElementById('changePasswordModal').classList.add('hidden');
    }
    
    /**
     * 处理添加用户
     */
    async handleAddUser() {
        const form = document.getElementById('addUserForm');
        const formData = new FormData(form);
        
        // 验证密码确认
        const password = formData.get('password');
        const confirmPassword = formData.get('confirmPassword');
        
        if (password !== confirmPassword) {
            this.showNotification('两次输入的密码不一致', 'error');
            return;
        }
        
        // 验证密码强度
        const strengthCheck = this.checkPasswordStrengthLocal(password);
        if (!strengthCheck.valid) {
            this.showNotification(strengthCheck.message, 'error');
            return;
        }
        
        try {
            const roleValue = formData.get('role_ids');
            let roleId = 2; // 默认普通用户
            if (roleValue === 'admin' || roleValue === '1') {
                roleId = 1; // 管理员
            } else if (roleValue === 'user' || roleValue === '2') {
                roleId = 2; // 普通用户
            }
            
            const userData = {
                username: formData.get('username'),
                email: formData.get('email'),
                password: password,
                full_name: formData.get('full_name'),
                phone: formData.get('phone'),
                role_ids: [roleId]
            };
            
            const response = await apiRequest('/api/users/', {
                method: 'POST',
                body: userData
            });
            
            if (response.code === 200) {
                this.hideAddUserModal();
                this.loadUsers();
                this.showNotification('用户创建成功', 'success');
            } else {
                this.showNotification(response.message || '用户创建失败', 'error');
            }
        } catch (error) {
            console.error('用户创建失败:', error);
            this.showNotification('用户创建失败', 'error');
        }
    }
    
    /**
     * 处理编辑用户
     */
    async handleEditUser() {
        const form = document.getElementById('editUserForm');
        const formData = new FormData(form);
        
        try {
            const userData = {
                email: formData.get('email'),
                full_name: formData.get('full_name'),
                phone: formData.get('phone'),
                role_ids: [parseInt(formData.get('role_ids'))],
                is_active: formData.get('is_active') === 'true'
            };
            
            const userId = formData.get('user_id');
            const response = await apiRequest(`/api/users/${userId}`, {
                method: 'PUT',
                body: userData
            });
            
            if (response.code === 200) {
                this.hideEditUserModal();
                this.loadUsers();
                this.showNotification('用户信息更新成功', 'success');
            } else {
                this.showNotification(response.message || '用户信息更新失败', 'error');
            }
        } catch (error) {
            console.error('用户信息更新失败:', error);
            this.showNotification('用户信息更新失败', 'error');
        }
    }
    
    /**
     * 处理修改密码
     */
    async handleChangePassword() {
        const form = document.getElementById('changePasswordForm');
        const formData = new FormData(form);
        
        const currentPassword = formData.get('current_password');
        const newPassword = formData.get('new_password');
        const confirmNewPassword = formData.get('confirm_new_password');
        
        if (newPassword !== confirmNewPassword) {
            this.showNotification('两次输入的新密码不一致', 'error');
            return;
        }
        
        // 验证密码强度
        const strengthCheck = this.checkPasswordStrengthLocal(newPassword);
        if (!strengthCheck.valid) {
            this.showNotification(strengthCheck.message, 'error');
            return;
        }
        
        try {
            const userId = formData.get('user_id');
            const response = await apiRequest(`/api/users/${userId}/change-password`, {
                method: 'POST',
                body: {
                    current_password: currentPassword,
                    new_password: newPassword
                }
            });
            
            if (response.code === 200) {
                this.hideChangePasswordModal();
                this.showNotification('密码修改成功', 'success');
            } else {
                this.showNotification(response.message || '密码修改失败', 'error');
            }
        } catch (error) {
            console.error('密码修改失败:', error);
            this.showNotification('密码修改失败', 'error');
        }
    }
    
    /**
     * 删除用户
     */
    async deleteUser(userId, username) {
        if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复。`)) {
            return;
        }
        
        try {
            const response = await apiRequest(`/api/users/${userId}`, {
                method: 'DELETE'
            });
            
            if (response.code === 200) {
                this.loadUsers();
                this.showNotification('用户删除成功', 'success');
            } else {
                this.showNotification(response.message || '用户删除失败', 'error');
            }
        } catch (error) {
            console.error('用户删除失败:', error);
            this.showNotification('用户删除失败', 'error');
        }
    }
    
    /**
     * 检查密码强度
     */
    checkPasswordStrength(password, elementId) {
        const result = this.checkPasswordStrengthLocal(password);
        const element = document.getElementById(elementId);
        
        if (result.valid) {
            element.innerHTML = `<span class="text-green-600"><i class="fas fa-check mr-1"></i>${result.message}</span>`;
        } else {
            element.innerHTML = `<span class="text-red-600"><i class="fas fa-times mr-1"></i>${result.message}</span>`;
        }
    }
    
    /**
     * 本地密码强度检查
     */
    checkPasswordStrengthLocal(password) {
        if (!password) {
            return { valid: false, message: '请输入密码' };
        }
        
        if (password.length < 8) {
            return { valid: false, message: '密码长度不能少于8个字符' };
        }
        
        if (password.length > 128) {
            return { valid: false, message: '密码长度不能超过128个字符' };
        }
        
        let hasUppercase = /[A-Z]/.test(password);
        let hasLowercase = /[a-z]/.test(password);
        let hasDigits = /\d/.test(password);
        let hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
        
        if (!hasUppercase) {
            return { valid: false, message: '密码必须包含大写字母' };
        }
        
        if (!hasLowercase) {
            return { valid: false, message: '密码必须包含小写字母' };
        }
        
        if (!hasDigits) {
            return { valid: false, message: '密码必须包含数字' };
        }
        
        if (!hasSpecial) {
            return { valid: false, message: '密码必须包含特殊字符' };
        }
        
        // 检查常见弱密码
        const weakPatterns = ['password', '123456', 'qwerty', 'abc123', 'admin', 'user', 'test', 'default'];
        if (weakPatterns.some(pattern => password.toLowerCase().includes(pattern))) {
            return { valid: false, message: '密码不能包含常见词汇' };
        }
        
        return { valid: true, message: '密码强度良好' };
    }
    
    /**
     * 验证密码确认
     */
    validatePasswordConfirm(passwordFieldName, confirmFieldName) {
        const form = document.querySelector(`input[name="${confirmFieldName}"]`).closest('form');
        const password = form.querySelector(`input[name="${passwordFieldName}"]`).value;
        const confirmPassword = form.querySelector(`input[name="${confirmFieldName}"]`).value;
        
        if (confirmPassword && password !== confirmPassword) {
            form.querySelector(`input[name="${confirmFieldName}"]`).setCustomValidity('两次输入的密码不一致');
        } else {
            form.querySelector(`input[name="${confirmFieldName}"]`).setCustomValidity('');
        }
    }
    
    /**
     * 格式化日期
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }
    
    /**
     * 获取当前用户信息
     */
    getCurrentUser() {
        // 从localStorage或cookie获取用户信息
        const userStr = localStorage.getItem('current_user');
        if (userStr) {
            try {
                return JSON.parse(userStr);
            } catch (e) {
                return { is_superuser: false };
            }
        }
        return { is_superuser: false };
    }
    
    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 ${
            type === 'success' ? 'bg-green-500' : 
            type === 'error' ? 'bg-red-500' : 
            type === 'warning' ? 'bg-yellow-500' : 'bg-blue-500'
        } text-white`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
}

// 全局函数，供HTML调用
let accountManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    accountManager = new AccountManager();
});

// 全局函数供HTML调用
function showAddUserModal() {
    accountManager.showAddUserModal();
}

function hideAddUserModal() {
    accountManager.hideAddUserModal();
}

function showEditUserModal(userId) {
    accountManager.showEditUserModal(userId);
}

function hideEditUserModal() {
    accountManager.hideEditUserModal();
}

function showResetPasswordModal(userId, username) {
    accountManager.showResetPasswordModal(userId, username);
}

function hideResetPasswordModal() {
    accountManager.hideResetPasswordModal();
}

function confirmResetPassword() {
    accountManager.confirmResetPassword();
}

function hideNewPasswordModal() {
    accountManager.hideNewPasswordModal();
}

function copyPassword() {
    accountManager.copyPassword();
}

function showChangePasswordModal(userId) {
    accountManager.showChangePasswordModal(userId);
}

function hideChangePasswordModal() {
    accountManager.hideChangePasswordModal();
}

function loadUsers() {
    accountManager.loadUsers();
}